import express from "express";
import bookHandler from "../handlers/booksHandler.js";

const router = express.Router();

// 统一错误处理
const handleAsync = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

// 添加书籍
router.post(
  "/",
  handleAsync(async (req, res) => {
    const book = await bookHandler.addBook(req.body);
    res.status(201).json(book);
  })
);

// 更新书籍
router.put(
  "/:id",
  handleAsync(async (req, res) => {
    const book = await bookHandler.updateBook(req.params.id, req.body);
    res.json(book);
  })
);

// 删除书籍
router.delete(
  "/:id",
  handleAsync(async (req, res) => {
    await bookHandler.deleteBook(req.params.id);
    res.status(204).end();
  })
);

// 书籍查询
router.get(
  "/",
  handleAsync(async (req, res) => {
    const books = await bookHandler.getBooks({
      name: req.query.name,
      minPrice: req.query.minPrice,
      maxPrice: req.query.maxPrice,
      includeCategory: true,
    });
    res.json(books);
  })
);

// ISBN查询
router.get(
  "/isbn/:isbn",
  handleAsync(async (req, res) => {
    const book = await bookHandler.getBookByISBN(req.params.isbn);
    res.json(book);
  })
);

// 书籍详情
router.get(
  "/:id",
  handleAsync(async (req, res) => {
    const book = await bookHandler.getBookDetails(req.params.id);
    res.json(book);
  })
);

// 错误处理中间件
// router.use((err, req, res, next) => {
//   console.error(err);
//   res.status(err.status || 500).json({
//     error: err.message || "Internal Server Error",
//   });
// });

export default router;
